﻿#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ServiceLocation;
using Newtonsoft.Utilities.Time;
using CommonServiceLocator = Microsoft.Practices.ServiceLocation.ServiceLocator;
using Newtonsoft.Utilities.Collections;
using Newtonsoft.Utilities.Text;
using System.Globalization;

namespace Newtonsoft.Utilities.Locator
{
  internal static class ServiceLocator
  {
    public static IServiceLocator Current
    {
      get
      {
        IServiceLocator current;
        try
        {
          current = CommonServiceLocator.Current;
        }
        catch (NullReferenceException)
        {
          NullServiceLocator nullServiceLocator = new NullServiceLocator();

          CommonServiceLocator.SetLocatorProvider(() => nullServiceLocator);

          current = nullServiceLocator;
        }

        return current;
      }
    }

    public static T GetInstance<T>()
    {
      T instance = GetInstanceSafe<T>();
      if (instance == null)
        throw new Exception("No instance of {0} registered.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));

      return instance;
    }

    public static T GetInstanceSafe<T>()
    {
      return Current.GetInstance<T>();
    }

    public static bool TryGetInstance<T>(out T instance)
    {
      if (!CanResolve<T>())
      {
        instance = default(T);
        return false;
      }

      instance = Current.GetInstance<T>();
      return true;
    }

    public static bool CanResolve<T>()
    {
      return (GetInstanceSafe<T>() != null);
    }


    public static IClock Clock
    {
      get { return GetInstanceSafe<IClock>() ?? SystemClock.Instance; }
    }
  }
}